package com.iqiyi.pps.epg.api.server.proxy;

import com.alibaba.fastjson.JSONObject;
import com.iqiyi.pps.epg.api.aop.annotation.SkipAuthCheck;
import com.iqiyi.pps.epg.api.aop.annotation.SkipInterfaceLog;
import com.iqiyi.pps.epg.api.model.web.query.TFilter;
import com.iqiyi.pps.epg.api.model.web.query.TPage;
import com.iqiyi.pps.epg.api.model.web.query.TResponse;
import com.iqiyi.pps.epg.api.model.web.ticket.*;
import com.iqiyi.pps.epg.api.server.web.ticket.TicketWebService;
import com.iqiyi.pps.epg.api.utils.Constants;
import com.iqiyi.pps.epg.api.utils.RegUtil;
import com.iqiyi.pps.epg.api.utils.ServiceUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by karkarrotxu on 2017/9/5.
 */
@Service
public class TicketProxy extends BaseProxy {
    private static Logger logger = LoggerFactory.getLogger(TicketProxy.class);

    @SkipInterfaceLog
    public String getLogList(String entityId, Integer pageNo, Integer pageSize) {
        String jsonStrResp = "";
        try {
            pageNo = (pageNo == null || pageNo < 1) ? 1 : pageNo;
            pageSize = (pageSize == null || pageSize < 1) ? 20 : pageSize;
            TicketWebService.Iface service = ServiceUtil.getTicketWebService();
            Map<String, String> params = new HashMap<>();
            TFilter tFilter = new TFilter();
            params.put("EQL_dataId", entityId);
            tFilter.setFilters(params);
            TPage page = new TPage(-1, pageNo, pageSize, "id", "desc", true);
            TTicketLogPage tTicketLogPage = service.searchLog(page, tFilter);
            if (tTicketLogPage != null) {
                jsonStrResp = Constants.getResponse(Constants.CODE_SUC, tTicketLogPage, "操作成功").toJsonString();
            } else {
                jsonStrResp = Constants.getJsonResponse(Constants.CODE_ERROR, null, PARAMETER_ERROR);
            }
        } catch (Exception e) {
            logger.error("[getLogList][error]", e);
            jsonStrResp = Constants.getJsonResponse(Constants.CODE_ERROR, null, INTERFACE_ERROR);
        }
        return jsonStrResp;
    }

    @SkipInterfaceLog
    public String getLogListByFilter(String paramsObj, Integer pageNo, Integer pageSize) {
        String jsonStrResp = "";
        try {
            pageNo = (pageNo == null || pageNo < 1) ? 1 : pageNo;
            pageSize = (pageSize == null || pageSize < 1) ? 20 : pageSize;
            TicketWebService.Iface service = ServiceUtil.getTicketWebService();
            Map<String, String> params = new HashMap<>();
            TFilter tFilter = new TFilter();
            if (paramsObj != null) {
                JSONObject jsonObject = JSONObject.parseObject(paramsObj);
                for (Map.Entry<String, Object> temp : jsonObject.entrySet()) {
                    params.put(temp.getKey(), temp.getValue() + "");
                }
            }
            tFilter.setFilters(params);
            TPage page = new TPage(-1, pageNo, pageSize, "id", "desc", true);
            TTicketLogPage tTicketLogPage = service.searchLog(page, tFilter);
            if (tTicketLogPage != null) {
                jsonStrResp = Constants.getResponse(Constants.CODE_SUC, tTicketLogPage, "操作成功").toJsonString();
            } else {
                jsonStrResp = Constants.getJsonResponse(Constants.CODE_ERROR, null, PARAMETER_ERROR);
            }
        } catch (Exception e) {
            logger.error("[getLogListByFilter][error]", e);
            jsonStrResp = Constants.getJsonResponse(Constants.CODE_ERROR, null, INTERFACE_ERROR);
        }
        return jsonStrResp;
    }

    @SkipAuthCheck
    public String addTicketData(String dataString) {
        try {
            TTicketData tTicketData = JSONObject.parseObject(dataString, TTicketData.class);
            if (tTicketData.getReporter() == null) {
                return ServiceUtil.getResponseFail("操作人员异常");
            }
            TResponse tResponse = getTicketWebService().addTicketData(tTicketData);
            if (tResponse == null) {
                return ServiceUtil.getResponseFail(INTERFACE_ERROR + ": no rpc response");
            }
            if (Constants.CODE_SUC.equals(tResponse.getCode())) {
                JSONObject errJson = JSONObject.parseObject(tResponse.getJsonData());
                long entityId = errJson.getLongValue("retValue");
                writeTicketLog(tTicketData.getId(), Constants.TicketLogType.TICKET_ADD.getIndex(), null, Constants.CODE_SUC + "|" + dataString);
                JSONObject data = new JSONObject();
                data.put("affectNum", 1);
                data.put("entityId", entityId);
                return Constants.getJsonResponse(Constants.CODE_SUC, data, "添加成功");
            } else {
                return ServiceUtil.getResponseFail("添加失败");
            }
        } catch (Exception e) {
            logger.error("addTicketData", e);
            return ServiceUtil.getResponseError(ERROR_EXIST);
        }
    }



    public String editTicketData(String dataString) {
        try {
            TTicketData tTicketData = JSONObject.parseObject(dataString, TTicketData.class);
            if(tTicketData.getId() == 0 ){
                return ServiceUtil.getResponseFail(PARAMETER_ERROR);
            }
            TResponse tResponse = getTicketWebService().editTicketData(tTicketData);
            String result = tResponse == null ? " no rpc response" : tResponse.getCode();
            writeTicketLog(tTicketData.getId(), Constants.TicketLogType.TICKET_EDIT.getIndex(), null, result + "|" + getStrParam());
            if (tResponse == null) {
                return ServiceUtil.getResponseFail(INTERFACE_ERROR + ": no rpc response");
            } else if (Constants.CODE_SUC.equals(tResponse.getCode())) {
                return Constants.getResponse(Constants.CODE_SUC, null, "修改成功").toJsonString();
            } else {
                return Constants.getJsonResponse(Constants.CODE_FAIL, null, tResponse.getMsg());
            }
        } catch (Exception e) {
            logger.error("editTicketData", e);
            return ServiceUtil.getResponseError(ERROR_EXIST);
        }
    }
    @SkipAuthCheck
    public String cancelTicketData(String dataString) {
        try {
            TTicketData tTicketData = JSONObject.parseObject(dataString, TTicketData.class);
            TResponse tResponse = getTicketWebService().cancelTicketData(tTicketData);
            if (tResponse == null) {
                return ServiceUtil.getResponseFail(INTERFACE_ERROR + ": no rpc response");
            } else if (Constants.CODE_SUC.equals(tResponse.getCode())) {
                return Constants.getResponse(Constants.CODE_SUC, null, "修改成功").toJsonString();
            } else {
                return Constants.getJsonResponse(Constants.CODE_FAIL, null, tResponse.getMsg());
            }
        } catch (Exception e) {
            logger.error("editTicketData", e);
            return ServiceUtil.getResponseError(ERROR_EXIST);
        }
    }


    @SkipInterfaceLog
    public String getTicketDataList(String paramsObj, Integer pageNo, Integer pageSize, String orderObj) {
        try {
            Map<String, String> params = new HashMap<>();
            if (paramsObj != null) {
                JSONObject jsonObject = JSONObject.parseObject(paramsObj);
                for (Map.Entry<String, Object> temp : jsonObject.entrySet()) {
                    params.put(temp.getKey(), temp.getValue() + "");
                }
            }
            TFilter tFilter = new TFilter();
            tFilter.setFilters(params);
            JSONObject orderJson = new JSONObject();
            orderJson.put("orderBy", "addTime");
            orderJson.put("order", "desc");
            if (orderObj != null && orderObj.length() > 2) {
                JSONObject jsonObject = JSONObject.parseObject(orderObj);
                orderJson.put("orderBy", jsonObject.getString("orderBy"));
                orderJson.put("order", jsonObject.getString("order"));
            }
            TPage page = new TPage(-1, pageNo, pageSize, orderJson.getString("orderBy"), orderJson.getString("order"), true);
            TTicketDataPage tTicketDataPage = getTicketWebService().searchTicketData(page, tFilter);
            if (tTicketDataPage == null) {
                return ServiceUtil.getResponseError(INTERFACE_ERROR);
            } else {
                return Constants.getResponse(Constants.CODE_SUC, tTicketDataPage, "操作成功").toJsonString();
            }
        } catch (Exception e) {
            logger.error("getTicketDataList", e);
            return ServiceUtil.getResponseError(ERROR_EXIST);
        }
    }

    public String assignTickData(String id, String executor) {
        try {
            if (executor == null || !RegUtil.isPositiveInteger(id)) {
                return ServiceUtil.getResponseFail(INTERFACE_ERROR);
            }
            Map<String, String> params1 = new HashMap<>();
            params1.put("EQS_type", "ticket_worker");
            params1.put("EQS_val", executor);
            TFilter tFilter1 = new TFilter();
            tFilter1.setFilters(params1);
            List<TTicketSysConfig> list = getTicketWebService().filterConfigs(tFilter1);
            if (list.size() == 0) {
                return ServiceUtil.getResponseError("不存在的执行人");
            }
            TResponse tResponse = getTicketWebService().assignTicketData(Long.valueOf(id), executor);

            String result = tResponse == null ? " no rpc response" : tResponse.getCode();
            writeTicketLog(Long.valueOf(id), Constants.TicketLogType.TICKET_ASSIGN.getIndex(), null, result + "|" + getStrParam());
            if (tResponse == null) {
                return ServiceUtil.getResponseFail(INTERFACE_ERROR + ": no rpc response");
            } else if (Constants.CODE_SUC.equals(tResponse.getCode())) {
                return Constants.getResponse(Constants.CODE_SUC, null, "修改成功").toJsonString();
            } else {
                return Constants.getJsonResponse(Constants.CODE_FAIL, null, tResponse.getMsg());
            }
        } catch (Exception e) {
            logger.error("[queryConfigs]", e);
            return getResponseWithJsonp(Constants.CODE_ERROR, null, INTERFACE_ERROR);
        }
    }

    @SkipInterfaceLog
    public String getCheckList(String dataId) {
        try {
            TResponse tResponse = getTicketWebService().getTicketLiveCheck(Long.valueOf(dataId));
            if (tResponse == null) {
                return ServiceUtil.getResponseFail(INTERFACE_ERROR + ": no rpc response");
            } else if (Constants.CODE_SUC.equals(tResponse.getCode())) {
                return Constants.getResponse(Constants.CODE_SUC, JSONObject.parseObject(tResponse.getJsonData()), "查询成功").toJsonString();
            } else {
                return Constants.getJsonResponse(Constants.CODE_FAIL, null, tResponse.getMsg());
            }
        } catch (Exception e) {
            logger.error("[queryConfigs]", e);
            return getResponseWithJsonp(Constants.CODE_ERROR, null, INTERFACE_ERROR);
        }
    }

    @SkipInterfaceLog
    public String queryConfigs(String paramsObj) {
        try {
            Map<String, String> params = new HashMap<>();
            if (paramsObj != null) {
                JSONObject jsonObject = JSONObject.parseObject(paramsObj);
                for (Map.Entry<String, Object> temp : jsonObject.entrySet()) {
                    params.put(temp.getKey(), temp.getValue() + "");
                }
            }
            TFilter tFilter = new TFilter();
            tFilter.setFilters(params);
            List<TTicketSysConfig> result = getTicketWebService().filterConfigs(tFilter);
            if (result != null) {
                return getResponseWithJsonp(Constants.CODE_SUC, result, null);
            } else {
                return getResponseWithJsonp(Constants.CODE_FAIL, null, "获取失败");
            }
        } catch (Exception e) {
            logger.error("[queryConfigs]", e);
            return getResponseWithJsonp(Constants.CODE_ERROR, null, INTERFACE_ERROR);
        }
    }

    public String submitLiveCheck(String dataString) {
        try {
            TTicketLiveCheck entity = JSONObject.parseObject(dataString, TTicketLiveCheck.class);
            TResponse tResponse = getTicketWebService().submitTicketLiveCheck(entity);
            String result = tResponse == null ? " no rpc response" : tResponse.getCode();
            int type = entity.getId() == 0 ? Constants.TicketLogType.CHECK_LIVE.getIndex() : Constants.TicketLogType.CHECK_LIVE_UPDATE.getIndex();
            writeTicketLog(entity.getDataId(), type, null, result + "|" + getStrParam());
            if (tResponse == null) {
                return ServiceUtil.getResponseFail(INTERFACE_ERROR + ": no rpc response");
            } else if (Constants.CODE_SUC.equals(tResponse.getCode())) {
                return Constants.getResponse(Constants.CODE_SUC, null, "操作成功").toJsonString();
            } else {
                return Constants.getJsonResponse(Constants.CODE_FAIL, null, tResponse.getMsg());
            }
        } catch (Exception e) {
            logger.error("submitLiveCheck", e);
            return ServiceUtil.getResponseError(ERROR_EXIST);
        }
    }
}
